package org.linlinjava.litemall.admin.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.linlinjava.litemall.db.dao.LitemallCarSeriesMapper;
import org.linlinjava.litemall.db.domain.LitemallCarBrand;
import org.linlinjava.litemall.db.domain.LitemallCarSeries;
import org.linlinjava.litemall.db.service.LitemallCarBrandService;
import org.linlinjava.litemall.db.service.LitemallCarSeriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;

@Controller
public class AdminCarSeriesService {


    @Autowired
    AdminCarModelService carModelService;

    @Autowired
    LitemallCarSeriesService litemallCarSeriesService;

    private final Log logger = LogFactory.getLog(AdminCarSeriesService.class);

    public void httpRequest(int brandid){
        //根据上一级brandId确定接口的api
        String apiPath = "https://www.autohome.com.cn/ashx/index/GetHomeFindCar.ashx?type=1&brandid="+brandid;
        //和上一级一样使用httpclient和httpget对接口发起请求并接受数据
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet post = new HttpGet(apiPath);
        try{
            post.addHeader("content-type","text/xml");
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //接受到的是字符串数据
                String detail = EntityUtils.toString(res.getEntity());
                //因为这个json串格式和上一个不一样,所以解析方法有点差别,需要嵌套解析,先用jsonObject解析json对象
                JSONObject jsonRequest = JSONObject.parseObject(detail);

                //在用jsonObject解析为json对象
                String result = jsonRequest.getString("result");
                JSONObject jsonObject = JSONObject.parseObject(result);

                //这个里面为json对象数组,jsonArray解析为json数组
                String fctlist = jsonObject.getString("fctlist");
                JSONArray jsonArray = JSONArray.parseArray(fctlist);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject fic =jsonArray.getJSONObject(i);
                    //嵌套解析,继续用jsonArray解析json对象,并遍历
                    String seriesList = fic.getString("serieslist");
                    JSONArray series = JSONArray.parseArray(seriesList);


                    for (int j = 0; j < series.size(); j++) {
                        //将实体对象实例化,并解析json对象
                        LitemallCarSeries carSeries = new LitemallCarSeries();
                        JSONObject ser = series.getJSONObject(j);
                        //将数据写入实体对象中
                        carSeries.setBrandId(brandid);
                        carSeries.setGroup(ser.getString("fctname"));
                        carSeries.setName(ser.getString("seriesName"));
                        int newId = ser.getInteger("seriesid");


                        int flag = 0;//在这里要加入一个判断是数据更新还是插入,flag为0代表是插入,flag为1代表更新
                        while (litemallCarSeriesService.findById(newId) != null){//先判断id是否被占用,如果没有被占用,可以直接插入
                            //从数据库获取id对应的一条数据
                            LitemallCarSeries car = litemallCarSeriesService.findById(newId);
                            //判断id和name是否同时xiangtong,若相同则可确定是要将数据更新,不同则id++继续进行下一次判断
                            if (car.getId() == newId && car.getName().equals(ser.getString("seriesName"))){

                                flag =1;
                                break;
                            }
                            newId++;
                        }
                        carSeries.setId(newId);
                        carSeries.setDeleted(String.valueOf(0));
                        int state = ser.getInteger("seriesState");
                        carSeries.setSellstate(state);

                        if (flag == 0){//0为插入数据
                            litemallCarSeriesService.add(carSeries);
                        }else {//1为更新数据
                            litemallCarSeriesService.updateById(carSeries);
                        }
                        //调用model里的方法,更新或插入model数据
                        //carModelService.httpRequest(carSeries.getId(),newId);
                        System.out.println(carSeries.getName());
                    }
                }

            }

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }



    }

}
